<template>
	<div>

		<div class="meeting-tools" :style="{ 'pointer-events': disabled ? 'none' : '' }">

			<div class="meeting-name">{{ meetingRoomName }}</div>

			<el-tooltip effect="dark" content="生成截图(Ctrl+R)" placement="top">
				<el-button class="screenshot-btn" type="info" title="生成截图" @keyup.ctrl.67="onScreenshot"
					@click="onScreenshot()" icon="el-icon-scissors" size="small" circle></el-button>
			</el-tooltip>
			<el-tooltip effect="dark" :content="toolStatus.audio.text" placement="top">
				<el-button :type="toolStatus.audio.type" :icon="toolStatus.audio.icon" size="small" circle
					@click="switchAudio()" :disabled="!audioDevices.length"> </el-button>
			</el-tooltip>
			<el-tooltip effect="dark" :content="toolStatus.video.text" placement="top">
				<el-button :type="toolStatus.video.type" :icon="toolStatus.video.icon" size="small" circle
					@click="switchCamera()" :disabled="!videoDevices.length"> </el-button>
			</el-tooltip>
			<el-tooltip effect="dark" :content="toolStatus.share.text" placement="top">
				<el-button class="share-btn" :disabled="!shareFlag" :type="toolStatus.share.type"
					:icon="toolStatus.share.icon" size="small" circle @click="switchShare()"> </el-button>
			</el-tooltip>
			<el-tooltip effect="dark" content="离开会议" placement="top">
				<el-button style="width: 66px;pointer-events: auto;" type="danger" icon="el-icon-phone" size="small"
					@click="leaveRoom"></el-button>
			</el-tooltip>
			<el-tooltip effect="dark" :content="toolStatus.record.text" placement="top">
				<el-button :type="toolStatus.record.type" :icon="toolStatus.record.icon" size="small" circle
					@click="switchRecord()"></el-button>
			</el-tooltip>
			<el-tooltip effect="dark" :content="toolStatus.screen.text" placement="top">
				<el-button class="screen-btn" :type="toolStatus.screen.type" :icon="toolStatus.screen.icon" size="small"
					circle @click="switchScreen()"></el-button>
			</el-tooltip>
			<el-popover placement="top" :append-to-body="false" title="更多设置" width="350" trigger="click">
				<el-descriptions title=" " :colon="false" direction="vertical" :column="1">
					<el-descriptions-item label="音频设备">
						<el-select v-model="audioIndex" :popper-append-to-body="false" placeholder="请选择"
							style="width: 100%;" @change="toggleAudio">
							<el-option v-for="(item, index) in audioDevices" :key="index" :label="item.label"
								:value="index">
							</el-option>
						</el-select>
					</el-descriptions-item>
					<el-descriptions-item label="视频设备">
						<el-select v-model="videoIndex" :disabled="!!isDevice" :popper-append-to-body="false"
							placeholder="请选择" style="width: 100%;" @change="toggleVideo">
							<el-option v-for="(item, index) in videoDevices" :key="index" :label="item.label"
								:value="index">
							</el-option>
						</el-select>
					</el-descriptions-item>
				</el-descriptions>
				<el-button slot="reference" icon="el-icon-s-tools" type="info" size="small" circle>
				</el-button>
			</el-popover>
		</div>


	</div>
</template>

<script>
import {
	startRecording,
	stopRecording,
	shareCapture
} from '@/api'
import {
	createScreenshot
} from '@/utils/tools.js'
import { Image } from 'element-ui'
export default {
	props: {
		OV: Object,
		publisher: Object,
		session: Object,
		disabled: {
			type: Boolean,
			default: false
		},
		meetingRoomName: String
	},
	data() {
		return {
			shareFlag: true, // 是否支持屏幕共享
			publishAudio: false, // 是否使用音频
			publishVideo: false, // 是否使用视频
			enableRecord: false, // 是否展开录制视频
			enableShare: false, // 是否共享屏幕
			isFullScreen: false, // 是否全屏

			// 设备信息
			videoDevices: [], // 视频输入设备列表
			audioDevices: [], // 音频输入设备列表
			audioIndex: 0,
			videoIndex: 0,
		}
	},
	computed: {
		toolStatus() {
			let audioFlag = this.publishAudio
			return {
				audio: {
					type: audioFlag ? 'success' : 'info',
					icon: `el-icon-${audioFlag ? 'microphone' : 'turn-off-microphone'}`,
					text: `${audioFlag ? '关闭麦克风' : '开启麦克风'}`
				},
				video: {
					type: this.publishVideo ? 'success' : 'info',
					icon: `el-icon-${this.publishVideo ? 'camera-solid' : 'camera'}`,
					text: `${this.publishVideo ? '关闭摄像头' : '开启摄像头'}`
				},
				share: {
					type: this.enableShare ? 'success' : 'info',
					icon: `el-icon-${this.enableShare ? 's-platform' : 'monitor'}`,
					text: `${this.enableShare ? '关闭共享屏幕' : '开启共享屏幕'}`
				},
				record: {
					type: this.enableRecord ? 'success' : 'info',
					icon: `el-icon-${this.enableRecord ? 'video-camera' : 'video-camera'}`,
					text: `${this.enableRecord ? '停止录制' : '开始录制'}`
				},
				screen: {
					type: this.isFullScreen ? 'success' : 'info',
					icon: `el-icon-${this.isFullScreen ? 'switch-button' : 'full-screen'}`,
					text: `${!this.isFullScreen ? '全屏' : '关闭全屏'}`
				}
			}
		}
	},
	mounted() {
		window.addEventListener('keydown', this.keyDownFunc) // 加入按键监听事件
		window.addEventListener('fullscreenchange', this.screenChangeFunc)

		this.$nextTick(() => {
			this.getDevices() // 获取音视频设备列表
			this.shareFlag = this.OV.checkScreenSharingCapabilities() // 获取是否支持屏幕共享
		})
	},
	beforeDestroy() {
		window.removeEventListener('fullscreenchange', this.screenChangeFunc)
		window.removeEventListener('keydown', this.keyDownFunc)
	},
	methods: {
		// 监听回车按键
		keyDownFunc(e) {
			if (e.ctrlKey && ['r', 'R'].includes(e.key)) {
				this.onScreenshot()
			}
		},
		// 监听页面是否全屏
		screenChangeFunc(e) {
			this.isFullScreen = !this.isFullScreen;
		},
		// 获取音视频设备列表
		getDevices() {
			this.OV.getDevices().then(devices => {
				console.log('设备列表：', devices);
				this.videoDevices = devices.filter(device => device.kind === "videoinput");
				this.audioDevices = devices.filter(device => device.kind === "audioinput");
				if (!this.audioDevices.length) {
					this.$message.error('请接入音频设备')
				}
			})
		},
		// 离开会议室
		leaveRoom() {
			this.$confirm('确认是否离开会议？', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				showCancelButton: true,
				type: 'warning',
				center: true
			}).then(() => {
				this.$router.push('/list')
			})
		},
		// 开关麦克风
		switchAudio() {
			if (!this.publisher) return
			this.publishAudio = !this.publishAudio
			this.publisher.publishAudio(this.publishAudio)
		},
		// 开关摄像头
		switchCamera() {
			if (!this.publisher) return
			this.publishVideo = !this.publishVideo
			this.publisher.publishVideo(this.publishVideo)
		},
		// 截图
		onScreenshot() {
			let canvasBox = document.getElementsByClassName('mian-video')[0]
			createScreenshot(canvasBox, false).then(filePath => {
				const blob = this.dataURLtoBlob(filePath)
				const file = this.blobToFile(blob, 'meetingCover')
				let formdata = new FormData()
				formdata.append('multipartFile', file)
				formdata.append('meetingRoomCode', this.$parent.meetingRoomCode)

				shareCapture(formdata).then(res => {
					console.log('会议室截图上传', res);
					this.$message.success('截图上传成功！')
				}).catch(err => {
					this.$message.error('截图上传失败！')
				})
			})
		},
		dataURLtoBlob(dataurl) {
			var arr = dataurl.split(','),
				mime = arr[0].match(/:(.*?);/)[1],
				bstr = atob(arr[1]),
				n = bstr.length,
				u8arr = new Uint8Array(n);
			while (n--) {
				u8arr[n] = bstr.charCodeAt(n);
			}
			return new Blob([u8arr], {
				type: mime
			});
		},
		//2,再将blob转换为file
		blobToFile(theBlob, fileName) {
			theBlob.lastModifiedDate = new Date(); // 文件最后的修改日期
			theBlob.name = fileName; // 文件名
			return new File([theBlob], fileName, {
				type: theBlob.type,
				lastModified: Date.now()
			});
		},
		// 切换麦克风
		async toggleAudio(index) {
			if (this.publisher) await this.session.unpublish(this.publisher) // 取消旧流
			const device = this.audioDevices[index]
			let newPublisher = this.OV.initPublisher(undefined, {
				audioSource: device.deviceId
			});
			this.$parent.toggleStream(() => {
				this.session.publish(this.$parent.publisher)
				this.audioIndex = index
			}, newPublisher)
		},
		// 视频切换处理
		async toggleVideo(index = 0, unType = true) {
			if (unType && this.publisher) await this.session.unpublish(this.publisher) // 取消旧流
			const device = this.videoDevices[index]
			let newPublisher = this.OV.initPublisher(undefined, {
				videoSource: device.deviceId,
				resolution: '1280x720',
				frameRate: 60, // 视频帧率
			});
			this.$parent.toggleStream(() => {
				this.session.publish(this.$parent.publisher)
				this.videoIndex = index
			}, newPublisher)
		},
		// 开关录制
		switchRecord() {
			if (!this.publisher) return this.$message('无法开启录制！')
			let data = {
				meetingRoomCode: this.$parent.meetingRoomCode
			}
			if (!this.enableRecord) {
				startRecording(data)
					.then(res => {
						this.$message.info('录制开始')
						this.enableRecord = true
					})
					.catch(err => this.$message.error(err.msg))

			} else {
				stopRecording(data)
					.then(res => {
						this.$message.info('录制停止')
						this.enableRecord = false
					})
					.catch(err => this.$message.error(err.msg))
			}
		},
		switchScreen() {
			if (this.isFullScreen) {
				let arr = ["exitFullscreen", "webkitCancelFullScreen", "mozCancelFullScreen", "msExitFullscreen",];
				document[arr.find((item) => !!document[item])]()
			} else {
				let arr = ["requestFullscreen", "webkitRequestFullScreen", "mozRequestFullScreen",
					"msRequestFullscreen",
				];
				const fullarea = document.getElementById('meeting-main');
				fullarea[arr.find((item) => !!fullarea[item])]()
			}
		},
		async switchShare() {
			if (!this.publisher) return this.$message('无法使用共享屏幕！')

			let publisher = this.OV.initPublisher(undefined, {
				videoSource: "screen"
			});

			// 停止视频流推送
			await this.session.unpublish(this.publisher)

			this.$parent.toggleStream(() => {
				this.$parent.publisher.once('accessAllowed', (event) => {
					// 监听共享屏幕是否停止
					this.publisher.stream.getMediaStream().getVideoTracks()[0]
						.addEventListener(
							'ended',
							async () => {
								console.log('分享停止');
								this.toggleVideo(0)
								this.enableShare = false
								this.publishVideo = true
							});

					// 推送共享屏幕视频流
					this.session.publish(this.publisher);
					this.enableShare = true
					this.publishVideo = false

				});
				// 共享屏幕失败
				this.$parent.publisher.once('accessDenied', (event) => {
					this.toggleVideo(0, false)
				});
			}, publisher)

		},
	}
}
</script>

<style lang="scss" scoped>
.meeting-tools {
	position: relative;
	display: flex;
	align-items: center;
	justify-content: center;
	background-color: #303030;
	margin: 0;
	padding: 15px 0;

	button {
		font-size: 20px;
		margin-left: 15px;
	}

	.meeting-name {
		position: absolute;
		left: 30px;
		top: 50%;
		transform: translate(0, -50%);
		color: #fff;
	}
}

/*定义竖屏 css*/
@media screen and (orientation:portrait) {
	.meeting-tools {
		position: fixed;
		bottom: 0;
		width: 100vw;
	}

	.screenshot-btn,
	.meeting-name,
	.screen-btn,
	.share-btn {
		display: none;
	}
}
</style>
